﻿using Ionic.Zip;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;

/// <summary>
/// FilePackage 的摘要说明
/// </summary>
public class FilePackage
{
    HttpContext context;
    JToken conf;

    public FilePackage(HttpContext context)
    {
        this.context = context;
        conf = (JToken)JsonConvert.DeserializeObject(File.ReadAllText(context.Server.MapPath("../Conf/FileSenderConf.json")));
    }

    public List<string> getZipPath()
    {
        List<string> res = new List<string>();

        string[] needPackingPaths = loadTransferFiles();
        foreach (string packingPath in needPackingPaths)
        {
            string packedZipPath = packingFile(packingPath);
            res.Add(packedZipPath);
        }

        return res;
    }

    private string[] loadTransferFiles()
    {
        JArray sendingDirects = (JArray)conf["sendingDirect"];
        string[] res = new string[sendingDirects.Count];
        for (int i = 0; i < res.Length; i++)
        {
            res[i] = sendingDirects[i].ToString();
        }
        return res;
    }

    private string packingFile(string filePath)
    {
        string zipSavingDirectory = conf["sendingPackZipPath"].ToString() + "\\" + DateTime.Today.ToString("yyyy-MM-dd");
        zipSavingDirectory = context.Server.MapPath("~/" + zipSavingDirectory);
        if (Directory.Exists(zipSavingDirectory) == false)
        {
            Directory.CreateDirectory(zipSavingDirectory);
        }

        
        string fileName = Path.GetFileName(filePath);
        string zipFile = zipSavingDirectory + "\\" + fileName + ".zip";

        int segement = Convert.ToInt32(conf["zipSegement"]);
        ZipHelper.Compress(filePath, zipFile, segement);

        return zipFile;
    }




}